package com.wantup.config;

import com.wantup.intecepter.HttpHandShakeIntecepter;
import com.wantup.intecepter.SocketChannelIntecpter;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * https://bbs.csdn.net/topics/392417235?page=1
 * https://blog.csdn.net/u014042066/article/details/76702120
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 需要注册一个注册一个站点
     *
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/zlw-websocket")//自己命名的名称
                .addInterceptors(new HttpHandShakeIntecepter())
                .setAllowedOrigins("*")//允许任何元素访问 可以设置自己的域名
                .withSockJS();

    }

    /**
     * 消息代理
     * setApplicationDestinationPrefixes  客户端连接服务端 一个前缀(客户端 向服务端 推送消息的前缀)
     * <p>
     * <p>
     * enableSimpleBroker 客户端订阅服务端的一个前缀(服务端向客户端推送消息的前缀)
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app_wantup");
        registry.enableSimpleBroker("/topic", "/topic2", "/chat");

    }

    /**
     * 可以配置websocket的 最大连接数
     *
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new SocketChannelIntecpter());
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.interceptors(new SocketChannelIntecpter());
    }
}
